package com.suwenhao.controller;


import com.alibaba.fastjson.JSONObject;
import com.suwenhao.constants.Constant;
import com.suwenhao.entity.User;
import com.suwenhao.enums.SessionEnum;
import com.suwenhao.service.UserService;
import com.suwenhao.utils.VerifyCode;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * @Author:suwenhao
 * @Description: 测试
 * @Date: Created in 2020/9/22 17:35
 */

@WebServlet("/img/*")
public class ImgServlet extends BaseServlet {

    private UserService userService = new UserService();

    protected void getImg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String pic = req.getParameter("pic");
        //完整路径=服务器路径+数据库保存的图片名称
        String realUrl = Constant.FILE_PREFIX + pic;
        File file = new File(realUrl);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        OutputStream os = resp.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = bis.read(b)) != -1) {
            os.write(b, 0, len);
        }
        os.flush();
        os.close();
        bis.close();


    }

    protected void updatePic(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String path = "";
        String pic = "";

        Map<String, String> map = new HashMap<>();

        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload sfu = new ServletFileUpload(factory);

        sfu.setFileSizeMax(1024 * 1024 * 2);

        PrintWriter out = resp.getWriter();


        try {
            List<FileItem> items = sfu.parseRequest(req);

            for (int i = 0; i < items.size(); i++) {
                FileItem item = items.get(i);
                //构造图片服务器路径
                if (!item.isFormField()) {
                    String name = item.getName();

                    String suffix = name.split("\\.")[1];
                    pic = UUID.randomUUID().toString().replace("-", "") + "." + suffix;


                    path = Constant.FILE_PREFIX + pic;

                    File file = new File(path);
                    if (!file.exists()) {
                        item.write(file);
                    }
                }
            }


//            修改数据库的pic
            HttpSession session = req.getSession();
            User loginUser = (User) session.getAttribute(Constant.SESSION_LOGIN);

            userService.updatePic(loginUser.getId(), pic);

            loginUser.setPic(pic);

            session.setAttribute(Constant.COOKIE_LOGIN, loginUser);


            map.put("code", "200");
            map.put("msg", pic);

//            out.write(200);
        } catch (Exception e) {
            map.put("code", "500");
            map.put("msg", "修改失败");
//            out.write(500);
        }
        out.write(JSONObject.toJSONString(map));


    }

    protected void getPicCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        VerifyCode verifyCode = new VerifyCode();

        BufferedImage image = verifyCode.getImage();

        String str = verifyCode.getText();

        //存session
        HttpSession session = req.getSession();

        session.setAttribute(SessionEnum.SESSION_PIC_CODE.getValue(),str);

        ImageIO.write(image, "JPEG", resp.getOutputStream());


        // 禁止图像缓存
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        resp.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中
        ServletOutputStream sos = resp.getOutputStream();
        ImageIO.write(image, "jpeg", sos);
        sos.flush();
        sos.close();

    }

}


